﻿using System;
using System.Collections.Generic;
using Framework;

namespace Game
{
    public class ResourceComponent : EventTarget, IComponent
    {
        public event Action Completed; 
        
        private string[] _urls;
        private Dictionary<string, Resource> _url2resourceDict = new Dictionary<string, Resource>();
        
        public void Load(params string[] urls)
        {
            Cancel();
            _urls = urls;
            for (int i = 0; i < _urls.Length; ++i)
            {
                ResManager.Instance.Load(_urls[i], OnLoadCompleted);
            }
        }

        public virtual void Cancel()
        {
            if (_urls == null)
            {
                return;
            }
            for (int i = 0; i < _urls.Length; ++i)
            {
                ResManager.Instance.Cancel(_urls[i], OnLoadCompleted);
            }

            foreach (KeyValuePair<string, Resource> url2resourcePair in _url2resourceDict)
            {
                url2resourcePair.Value.Release();
            }
            _urls = null;
            _url2resourceDict.Clear();
        }
        
        public override void Dispose()
        {
            base.Dispose();
            Cancel();
            Completed = null;
        }

        public Resource GetResource(string url)
        {
            return _url2resourceDict[url];
        }

        protected virtual void OnLoadCompleted(Resource resource)
        {
            resource.Retain();
            _url2resourceDict.Add(resource.url, resource);
            if (_url2resourceDict.Count == _urls.Length)
            {
                Completed.SafeInvoke();
            }
        }
    }
}